// Fill out your copyright notice in the Description page of Project Settings.

#include "Isalong2.h"
#include "ElecUnitBase.h"




AElecUnitBase::AElecUnitBase()
{
	_splMesh = CreateDefaultSubobject<USplineMeshComponent>(TEXT("SPMesh"));

	// attach basic mesh to component
	_skMesh->AttachTo(_rayTraceBox);
	_stMesh->AttachTo(_rayTraceBox);
	_splMesh->AttachTo(_rayTraceBox);
}

bool AElecUnitBase::IsProvider()
{
	return _asProvider;
}

bool AElecUnitBase::ConstValue()
{
	return _constVal;
}

void AElecUnitBase::OnFireBegin()
{
	for (int i=0;i<_buildingLogics.Num();i++)
	{
		if (_buildingLogics[i]->Get_Override_OnFireBegin())
		{
			_buildingLogics[i]->OnFireBegin();
			return;
		}
	}
}

void AElecUnitBase::OnFireEnd()
{
	for (int i = 0; i < _buildingLogics.Num(); i++)
	{
		if (_buildingLogics[i]->Get_Override_OnFireEnd())
		{
			_buildingLogics[i]->OnFireEnd();
			return;
		}
	}
}

void AElecUnitBase::Tick(float DeltaSeconds)
{
	Super::Tick(DeltaSeconds);
	for (int i=0;i<_buildingLogics.Num();i++)
	{
		if (_buildingLogics[i]->Get_UseLogicTick())
		{
			_buildingLogics[i]->LogicTick(DeltaSeconds);
		}
	}

	if (ToolSurfaceSnap())
	{
		_canPlace = true;
		return;
	}
	_canPlace = false;
	ToolGoBack();
}

void AElecUnitBase::SetUpData(FInteractData* data, int itemType)
{
	Super::SetUpData(data, itemType);
	_dataPack = (FElecData*)data;
	// set up the static mesh data
	if (_dataPack->_useSplineMesh)
	{
		_splMesh->SetStaticMesh(_dataPack->_buildingMesh);
	}
	else
	{
		_stMesh->SetStaticMesh(_dataPack->_buildingMesh);
	}
	_skMesh->SetSkeletalMesh(_dataPack->_buildingSkMesh);
	_rayTraceBox->SetBoxExtent(_dataPack->_rayTraceBoxExtent);
	_overlapBox->SetBoxExtent(_dataPack->_overlapBoxExtent);

	// construct logic
	TArray<UClass*> logics = _dataPack->_elecLogics;
	for (int i = 0; i<logics.Num(); i++)
	{
		UElecCustomLogicBase* elecLogicComponent = ConstructObject<UElecCustomLogicBase>(logics[i], this);
		if (elecLogicComponent)
		{
			elecLogicComponent->RegisterComponent();
			elecLogicComponent->Init(this);
			_buildingLogics.Add(elecLogicComponent);
		}
	}
}

void AElecUnitBase::OnUnitBeginOverlap(AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult)
{
	if (Cast<AElecUnitBase>(OtherActor)!=nullptr)
	{
		_otherUnits.Add(Cast<AElecUnitBase>(OtherActor));
		OnUnitBeginOverlapHelp(Cast<AElecUnitBase>(OtherActor));
	}
}

void AElecUnitBase::OnUnitEndOverlap(AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex)
{
	if (Cast<AElecUnitBase>(OtherActor)!=nullptr)
	{
		_otherUnits.Remove(Cast<AElecUnitBase>(OtherActor));
		OnUnitEndOverlapHelp(Cast<AElecUnitBase>(OtherActor));
	}
}
